const express = require('express')
const path = require('path')
const app = express()

//处理body请求体的中间件
app.use(express.urlencoded())
app.use(express.json())

//查询学生信息接口
app.get('/user', (req, res) => {
    const {
        userId
    } = req.query;

    //如果查询失败
    if (userId !== '001') {
        return res.send({
            code: 10001,
            msg: '查询失败',
            data: null
        })
    }
    res.send({
        code: 1000,
        msg: '查询成功',
        data: {
            name: 'xiaomei',
            age: 18,
            sex: '男'
        }
    })
})

//get请求
app.get('/userInfo', (req, res) => {
    const {
        userId
    } = req.query;

    //如果查询失败
    if (userId !== '001') {
        return res.send({
            code: 10001,
            msg: '查询失败',
            data: null
        })
    }
    //查询成功响应
    res.send({
        code: 10000,
        msg: '查询成功',
        data: {
            name: 'xiaomei',
            age: 18,
            sex: '男'
        }
    })
})

app.post("/adduser", (req, res) => {
    console.log("adduser");
    console.log(req.body, "req.body");
    console.log(req.query, "req.query");
    const {
        name,
        age,
        sex
    } = req.body;

    if (!name || !age || !sex) {
        return res.send({
            code: 10001,
            mes: "添加失败",
            data: null
        })
    }

    res.send({
        code: 10000,
        mes: "添加成功",
        data: null
    })
})


//静态资源部署接口
app.get('/1', (req, res) => {
    const filePath = path.resolve(__dirname, './01.ajax方法.html')
    res.sendFile(filePath)
})

app.get("/2", (req, res) => {
    const filePath = path.resolve(__dirname, "./02.ajax的二级封装.html");
    res.sendFile(filePath);
})
app.listen(8000, () => {
    console.log('服务器请求成功 请访问http://127.0.0.1:8000');
})